package cnki.tpi.kbatis.utils;


import cnki.tpi.kbatis.config.Configuration;
import cnki.tpi.kbatis.io.Resources;
import cnki.tpi.kbatis.sqlsession.SqlSession;
import cnki.tpi.kbatis.sqlsession.SqlSessionFactory;
import cnki.tpi.kbatis.sqlsession.SqlSessionFactoryBuilder;
import cnki.tpi.util.ConstantUtil;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: DataSourceUtil
 * Description:
 *
 * @author 小黄
 * date: 2019/11/19 17:25
 */
@Component
public class DataSourceUtil {

    private static SqlSession sqlSession = null;

    /**
     * 用于获取一个连接
     *
     * @param cfg
     * @return
     */
    public static Connection getConnection(Configuration cfg) {
        try {
            Class.forName(cfg.getDriver());
            return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSqlSession() {
        if (sqlSession == null) {
            InputStream inputStream = Resources.getResourcesAsStream(ConstantUtil.KBATIS_LOCATION);
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        }
        return sqlSession;
    }

    /**
     * 获取包括父类(非Object)的所有field
     *
     * @param resultTypeClass
     * @return
     */
    public static List<Field> getFields(Class<?> resultTypeClass) {
        //取出resultTypeObject所有字段
        List<Field> fields = new ArrayList<>();
        //当父类为null的时候说明到达了最上层的父类(Object类).
        while (resultTypeClass != null && !resultTypeClass.getName().toLowerCase().equals("java.lang.object")) {
            fields.addAll(Arrays.asList(resultTypeClass.getDeclaredFields()));
            resultTypeClass = resultTypeClass.getSuperclass(); //得到父类,然后赋给自己
        }
        return fields;
    }
}